package logics

import (
	"backenddev/shop_server/internal/defs"
	"backenddev/shop_server/internal/models"
	"backenddev/shop_server/pkg/mysqldb"
	"backenddev/shop_server/utils"
	"fmt"
)

// adminLogin 登录
func AdminLogin(username, password string) (*models.Admin, *defs.AppError) {
	admin := models.Admin{}
	query := mysqldb.Mysql.Where("username = ?", username).First(&admin)
	if query.RowsAffected == 0 {
		return nil, defs.Error_UserNotFind
	}
	if admin.Password != utils.MD5String(password) {
		return nil, defs.Error_UserNameOrPswError
	}
	admin.Password = ""
	return &admin, nil
}

func GetUserDetail(uid int64) (*models.User, error) {
	user := &models.User{}
	query := mysqldb.Mysql.Where("uid = ?", uid).First(user)
	if query.RowsAffected == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	user.Password = ""
	return user, nil
}

// 拉黑用户
func BlockUser(uid int64, reason string) (bool, error) {
	query := mysqldb.Mysql.Create(&models.BlackListUid{Uid: uid, Reason: reason})
	return query.RowsAffected > 0, query.Error
}

// 解禁用户
func UnBlockUser(uid int64) (bool, error) {
	query := mysqldb.Mysql.Where("uid = ?", uid).Delete(&models.BlackListUid{})
	return query.RowsAffected > 0, query.Error
}

// 统计活跃用户:1日活跃用户  3日前活跃用户  7日前活跃用户
func GetActiveUser() (int64, int64, int64, error) {
	oneDayUsers := int64(0)
	//updated_at > startTime updated_at < endTime
	query := mysqldb.Mysql.Model(&models.User{}).Where("updated_at > ?", utils.GetStartTime(1)).Where("updated_at < ?", utils.GetEndTime(1)).Count(&oneDayUsers)
	if query.Error != nil {
		return 0, 0, 0, query.Error
	}
	threeDayUsers := int64(0)
	query = mysqldb.Mysql.Model(&models.User{}).Where("updated_at > ?", utils.GetStartTime(3)).Where("updated_at < ?", utils.GetEndTime(3)).Count(&threeDayUsers)
	if query.Error != nil {
		return 0, 0, 0, query.Error
	}
	sevenDayUsers := int64(0)
	query = mysqldb.Mysql.Model(&models.User{}).Where("updated_at > ?", utils.GetStartTime(7)).Where("updated_at < ?", utils.GetEndTime(7)).Count(&sevenDayUsers)
	return oneDayUsers, threeDayUsers, sevenDayUsers, query.Error
}

func SearchUser(uid int64, nickName string, phone string) ([]*models.User, error) {
	users := []*models.User{}
	user := &models.User{}
	query := mysqldb.Mysql.Table(user.TableName())
	if uid != 0 {
		query = query.Where("uid = ?", uid)
	}
	if nickName != "" {
		query = query.Where("nickname like ?", "%"+nickName+"%")
	}
	if phone != "" {
		query = query.Where("phone like ?", "%"+phone+"%")
	}
	query = query.Find(&users)
	return users, query.Error
}
